package ca.unbc.cpsc672.rcmd;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

public class DBUtils {
	public static final String DERBY_URL = "jdbc:derby:yelpdb;create=true";

	// stars increases 0.1 when user like it
	public static void like(String id) throws SQLException {
		new org.apache.derby.jdbc.EmbeddedDriver();
		try (Connection conn = DriverManager.getConnection(DERBY_URL)) {
			String sql = "update yelp_data set stars = stars + 0.1 where id = ?";
			try (PreparedStatement stmt = conn.prepareStatement(sql)) {
				stmt.setString(1, id);
				stmt.executeUpdate();
			}
		}
	}

	public static BusinessInfo[] getInfo() throws SQLException {
		new org.apache.derby.jdbc.EmbeddedDriver();
		try (Connection conn = DriverManager.getConnection(DERBY_URL)) {
			LinkedList<BusinessInfo> ret = new LinkedList<>();
			String sql = "select * from yelp_data";
			try (ResultSet rs = conn.createStatement().executeQuery(sql)) {
				while (rs.next()) {
					BusinessInfo info = new BusinessInfo(rs);
					ret.add(info);
				}
			}
			return ret.toArray(new BusinessInfo[0]);
		}
	}

	public static void reset() throws SQLException {
		new org.apache.derby.jdbc.EmbeddedDriver();
		try (Connection conn = DriverManager.getConnection(DERBY_URL)) {
			try (Statement stmt = conn.createStatement()) {
				stmt.execute("delete from yelp_data");
				stmt.execute("insert into yelp_data select * from yelp_data_default");
			}
		}
	}
}
